<?php

namespace common\models\service;

use common\cache\DictCache;
use common\components\OrderBehavior;
use common\helpers\commonApi;
use common\helpers\QueueApi;
use common\helpers\TransformApi;
use common\models\Order;
use common\models\OrderGoods;
use common\models\OrderLog;
use common\models\OrderReceiv;
use common\models\System;
use common\models\User;
use common\models\UserCoupon;
use yii\db\Exception;
use yii\helpers\ArrayHelper;
use Yii;

class OrderService extends Order
{
    /**
     * 后台列表
     * @param $where
     * @return array|string
     */
    public static function getOperList($where)
    {
        $back = new BaseController();
        $back->model = Order::className();
        $return = $back->actionIndex(true, $where, ['create_time' => 'desc']);
        $list = $return['data'];
        //支付状态
        $pay_status = DictCache::get('pay_status');
        //订单状态
        $order_status = DictCache::get('order_status');
        //用户信息
        $delivery_method = DictCache::get('delivery_method');
        $userids = array_unique(ArrayHelper::getColumn($list, 'userid'));
        $userInfo = (new User())->getUserHtml($userids);
        $ids = array_column($list,'id');
        $spec = (new OrderGoods())->getHtml($ids);
        foreach ($list as $key => $val) {
            $val['pay_status_name'] = $pay_status[$val['pay_status']] ?? '';
            $val['order_status_name'] = $order_status[$val['order_status']] ?? '';
            $val['pay_time'] = $val['pay_time'] ?? '';
            $val['good_html'] = $spec[$val['id']]??'';
            $val['user_html'] = $userInfo[$val['userid']]??'';
            $val['delivery_method_title'] = $delivery_method[$val['delivery_method']]??'';
            $receipt_info = $val['receipt_info']?json_decode($val['receipt_info'],true):[];
            $val['address'] = '';
            if ($val['delivery_method']==2){
                $val['address'] = "<div>提货方式：".$val['delivery_method_title']."</div>";
                $val['address'] .= "<div>校区：".$receipt_info['campus_name'].'<div>';
                $val['address'] .= "<div>收货人：".$receipt_info['consignee'].'<div>';
                $val['address'] .= "<div>联系方式：".$receipt_info['mobile'].'<div>';
                $val['address'] .= "<div>楼号/门牌号：".$receipt_info['address'].'<div>';
            }else{
                $val['address'] = "<div>提货方式：".$val['delivery_method_title']."</div>";
            }
            $list[$key] = $val;
        }
        $return['data'] = $list;
        return $return;
    }

    /**
     * 详情
     * @param $where
     * @return array
     */
    public static function detail($where)
    {
        $data = Order::find()->where($where)->asArray()->one();
        if (!$data) {
            $back = new BaseController();
            return $back->bError('订单错误');
        }
        $userids[] = $data['userid'];
        if ($data['one_level']){
            $userids[] = $data['one_level'];
        }
        if ($data['second_level']){
            $userids[] = $data['second_level'];
        }
        if ($data['top_level']){
            $userids[] = $data['top_level'];
        }
        $res = (new User())->getUserHtml($userids,1);
        $specAll = (new OrderGoods())->getList($data['id']);
        $spec = $specAll[$data['id']]??[];
        $pay_status = DictCache::get('pay_status');
        $order_status = DictCache::get('order_status');
        $delivery_method = DictCache::get('delivery_method');
        $astrict_sex = DictCache::get('astrict_sex');
        $refund_status = DictCache::get('refund_status');
        $receiv_status = DictCache::get('receiv_status');
        $order_log_type = DictCache::get('order_log_type');
        $log = OrderLog::find()->where(['order_sn'=>$data['order_sn']])->orderBy(['create_time'=>SORT_ASC])->asArray()->all();
        $receipt_info = $data['receipt_info']?json_decode($data['receipt_info'],true):[];
        $receiv = OrderReceiv::find()->where(['order_sn'=>$data['order_sn']])->orderBy(['create_time'=>SORT_DESC])->asArray()->all();
        return [
            'pay_status'=>$pay_status,'order_status'=>$order_status,
            'delivery_method'=>$delivery_method,'astrict_sex'=>$astrict_sex,
            'refund_status'=>$refund_status,'receiv_status'=>$receiv_status,
            'spec'=>$spec,'data'=>$data,'log'=>$log,'order_log_type'=>$order_log_type,
            'res'=>$res,'receipt_info'=>$receipt_info,'receiv'=>$receiv
        ];
    }

    /**
     * 订单发货
     * @param $orderSn
     * @param $type
     * @param $handle_id
     * @param $handle_name
     * @return array|mixed
     */
    public static function deliver($orderSn,$type,$handle_id,$handle_name)
    {
        if (!$orderSn){
            return commonApi::message('请选择要发货的订单',false);
        }
        $model = self::find()->where(['order_sn'=>$orderSn])->one();
        if (!$model){
            return commonApi::message('订单不存在',false);
        }
        if ($model->delivery_method==1){
            $order_receiv = System::getModel()->order_receiv??0;
            $order_receiv = $order_receiv*60*60;
            $model->order_status = 4;
            TransformApi::tx(function ()use ($model,$type,$handle_id,$handle_name,$order_receiv){
                if ($model->save()){
                    OrderLog::add($type,$model->order_sn,$handle_id,$handle_name,'自提订单发货','自提订单发货');
                    if ($order_receiv>0){
                        $callable = new OrderBehavior([
                            'method' => OrderBehavior::ORDER_RECEIV,
                            'params' => ['order_sn'=>$model->order_sn],
                        ]);
                        (new QueueApi())->delay($order_receiv,$callable);
                    }
                    return commonApi::message('发货成功');
                }
                throw new Exception('');
            },$result);
            return $result;
        }
        return commonApi::message('订单不支持直接发货',false);
    }

    /**
     * 修改支付金额
     * @param $orderSn
     * @param $pay_amount
     * @param $type
     * @param $handle_id
     * @param $handle_name
     * @return array|mixed
     */
    public static function editAmount($orderSn,$pay_amount,$type,$handle_id,$handle_name)
    {
        if ($pay_amount<=0){
            return commonApi::message('支付金额必须大于0',false);
        }
        $model = self::find()->where(['order_sn'=>$orderSn])->one();
        if (!$model){
            return commonApi::message('订单不存在',false);
        }
        if ($model->pay_status!==0){
            return commonApi::message('该订单不能修改支付金额',false);
        }
        $old = $model->pay_amount;
        $model->pay_amount = $pay_amount;
        TransformApi::tx(function ()use ($old,$model,$type,$handle_id,$handle_name){
            if ($model->save()!==false){
                if ($old-$model->pay_amount!==(float)0){
                    $callable = new OrderBehavior([
                        'method' => OrderBehavior::ORDER_DIS,
                        'params' => ['order_sn' => $model->order_sn, 'userid' => $model->userid],
                    ]);
                    (new QueueApi())->delay(0,$callable);
                    OrderLog::add($type,$model->order_sn,$handle_id,$handle_name,"修改付款金额","修改付款金额：修改前（{$old}），修改后（{$model->pay_amount}）");
                }
                return commonApi::message('修改成功');
            }
            throw new Exception('修改失败');
        },$result);
        return $result;
    }

    /**
     * 关闭订单
     * @param $order_sn
     * @param $type
     * @param $handle_id
     * @param $handle_name
     * @return array
     */
    public static function cancel($orderSn,$type,$handle_id,$handle_name)
    {
        $model = Order::find()->where(['order_sn' => $orderSn])->one();
        if (!$model) {
            return commonApi::message('订单错误', false);
        }
        if ($model->pay_status !== 0) {
            return commonApi::message('该订单不能关闭', false);
        }
        $model->pay_status = 2;
        TransformApi::tx(function ()use ($model,$type,$handle_id,$handle_name){
            if ($model->save()){
                if ($model->coupon_id){
                    UserCoupon::updateAll(['order_sn'=>'','use'=>0,'use_time'=>''],['id'=>$model->coupon_id]);
                }
                OrderLog::add($type,$model->order_sn,$handle_id,$handle_name,'关闭订单','关闭订单');
                return commonApi::message('关闭成功');
            }
            throw new Exception('关闭失败');
        },$result);
        return $result;
    }

    /**
     * 获取成交
     * @param $start_time
     * @param $end_time
     * @param $campus_id
     * @return int[]
     */
    public static function deal($start_time,$end_time,$campus_id)
    {
        $where = [];
        if ($start_time&&$end_time){
            $where = ['between','create_time',$start_time,$end_time];
        }
        $order = Order::find()
            ->where($where)
            ->andWhere(['pay_status'=>1])
            ->andFilterWhere(['campus_id'=>$campus_id])
            ->select(['sum(pay_amount) as amount','count(*) as num'])
            ->asArray()->one();
        $amount = $order['amount']??0;
        $num = $order['num']??0;
        return ['amount'=>$amount,'num'=>$num];
    }
}